import os
import subprocess
import sys
from typing import Optional

def get_platform():
    platform = sys.platform
    if platform.startswith("linux"):
        return "linux"
    elif platform.startswith("win"):
        return "windows.exe"
    elif platform.startswith("darwin"):
        return "mac"
    else:
        return platform

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
PLATFORM = get_platform()
DEFAULT_TRACE_STREAMER_DIR = os.path.join(CURRENT_DIR, "bin", "trace_streamer_binary")
TRACE_STREAMER_ENV_VAR = "TRACE_STREAMER_DIR"

# 把 db 放到系统 /tmp/cold_start_analyzer_db 目录下
DB_DIR = os.path.join(os.path.expanduser("~"), "tmp/cold_start_analyzer_db")
os.makedirs(DB_DIR, exist_ok=True)

def resolve_trace_streamer_dir(override: Optional[str] = None) -> str:
    if override:
        return os.path.abspath(override)
    env_dir = os.getenv(TRACE_STREAMER_ENV_VAR)
    if env_dir:
        return os.path.abspath(env_dir)
    return DEFAULT_TRACE_STREAMER_DIR

def resolve_trace_streamer_executable(override: Optional[str] = None):
    base_dir = resolve_trace_streamer_dir(override)
    exe_path = os.path.join(base_dir, f"trace_streamer_{PLATFORM}")
    return exe_path, base_dir


def convert_ftrace_to_sqlite(file_path: str, trace_streamer_dir: Optional[str] = None):
    ftrace_name = os.path.basename(file_path)
    file_abs_path = os.path.abspath(file_path)
    target_name = os.path.abspath(f"{DB_DIR}/{ftrace_name}.db")
    if os.path.exists(target_name):
        return target_name
    try:
        exe_path, base_dir = resolve_trace_streamer_executable(trace_streamer_dir)
        env = os.environ.copy()
        lib_path = os.path.join(base_dir, "lib")
        if PLATFORM == "linux" and os.path.exists(lib_path):
            existing = env.get("LD_LIBRARY_PATH")
            env["LD_LIBRARY_PATH"] = f"{lib_path}:{existing}" if existing else lib_path
        if not os.path.exists(exe_path):
            raise FileNotFoundError(f"trace_streamer executable missing: {exe_path}")
        command = [exe_path, file_abs_path, "-e", target_name]
        result = subprocess.run(command, env=env, capture_output=True, text=True)
        if result.returncode != 0:
            raise RuntimeError(
                f"Failed to convert ftrace to sqlite (code {result.returncode}): "
                f"{result.stderr or result.stdout}"
            )
        return target_name
    except Exception as e:
        print(f"Error converting ftrace to sqlite: {e}")
        return None
